<template>
  <a-tabs editable @delete="handleDelete" auto-switch :active-key="currentSelectKey" hide-content class="tabs-btns" @tab-click="showTargetView">
    <a-tab-pane v-for="(item, index) of tabsList" :key="item.path" :title="item?.meta?.locale" :closable="!item.isDefault" />
  </a-tabs>
</template>

<script lang="ts">
import { defineComponent, computed, watch, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useTabsStore, useAppStore } from "@/store";

export default defineComponent({
  name: "TabsView",
  setup() {
    const router = useRouter();
    const defaultKey = ref("");
    const store = useTabsStore();
    const appStore = useAppStore();
    const tabsList = computed(() => store.getTabs);
    const currentSelectKey = ref();

    const handleDelete = (val: any, ev: any) => {
      const lastRouter = store.removeTab(val);
      showTargetView(lastRouter.path);
    };

    const showTargetView = (key: string) => {
      router.push({ path: key });
    };

    onMounted(() => {
      window.addEventListener("beforeunload", () =>
        store.saveTabs(appStore.tabs)
      );
      store.loadTabs();
    });

    watch(
      () => router.currentRoute,
      (nv, ov) => {
        currentSelectKey.value = nv.value.path;
        if (nv.value.name !== "login") {
          store.addTab(nv.value);
        }
      },
      { immediate: true, deep: true }
    );

    return {
      handleDelete,
      showTargetView,
      defaultKey,
      currentSelectKey,
      tabsList,
    };
  },
});
</script>

<style lang="less" scoped>
.tabs-btns {
  margin: 0 5px;
}
</style>
